package io.github.ali.commons.exception;

import io.github.ali.commons.code.ExceptionCode;
import io.github.ali.commons.code.RespCode;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @author ALi
 * @version 1.0
 * @date 2024-06-06 10:58
 * @description
 */
public class MessageBuilderManager {
    private static MessageBuilder DEFAULT_MESSAGE_BUILDER;
    private static List<MessageBuilder> MESSAGE_BUILDER_LIST;
    static {
        DEFAULT_MESSAGE_BUILDER = (expressibleException, message) -> {
            ExceptionCode exceptionCode = expressibleException.getExceptionCode();
            StringBuilder messageBuilder = new StringBuilder();
            messageBuilder.append(exceptionCode.getErrorMsg());
            messageBuilder.append("(");
            messageBuilder.append(exceptionCode.getErrorCode());
            messageBuilder.append(")");
            messageBuilder.append(" ; Response : ");
            RespCode respCode = exceptionCode.getRespCode();
            messageBuilder.append(StringUtils.isEmpty(message) ? respCode.getMessage() : message);
            messageBuilder.append("(");
            messageBuilder.append(respCode.getCode());
            messageBuilder.append(")");
            return messageBuilder.toString();
        };
        MESSAGE_BUILDER_LIST = new ArrayList<>();

        ServiceLoader<MessageBuilder> serviceLoader = ServiceLoader.load(MessageBuilder.class);
        serviceLoader.iterator().forEachRemaining(MESSAGE_BUILDER_LIST::add);
    }
    static MessageBuilder getMessageBuilder(Exception exception) {
        for (MessageBuilder messageBuilder : MESSAGE_BUILDER_LIST) {
            if(messageBuilder.getExceptionType().isAssignableFrom(exception.getClass())) {
                return messageBuilder;
            }
        }
        return DEFAULT_MESSAGE_BUILDER;
    }
    public static MessageBuilder getDefaultMessageBuilder() {
        return DEFAULT_MESSAGE_BUILDER;
    }
}
